<?php
namespace app\logic;

use yii;
use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\common\PayUtil;
use app\models\Goods;
use app\models\Mall;
use app\models\OrderGoods;
use app\models\Order;
use app\models\Refund;
use Beanstalk\Client;


class OrderLogic
{

    public function createOrderNo(){
        return date('Ymd').mt_rand(100000,999999);
        /*$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));*/
    }

    public function submitOrder($user_id,$mall_id,$goods_id,$goods_num,$order_amount,$consignee,$shipping_mobile,$shipping_address,$id_card='',$user_remark='',&$order_no,&$order_time,&$goods_name){
        $order_no = $this->createOrderNo();
        $goods = Goods::find()->where(['goods_id'=>$goods_id,'goods_status'=>1,'is_del'=>0])->asArray()->one();
        if(!$goods)
            return false;
        $goods_name = $goods['goods_name'];
        $order = new Order();
        $order->order_no = $order_no;
        $order->mall_id = $mall_id;
        $order->goods_id = $goods_id;
        $order->goods_num = $goods_num;
        $order->goods_amount = $goods['real_price']*$goods_num;
        $order->order_amount = $order_amount;
        $order->user_id = $user_id;
        $order_time = date('Y-m-d H:i:s');
        $order->order_time = $order_time;
        $order->update_time = $order_time;
        $order->order_status = 0;
        $order->shipping_status = 0;
        $order->consignee = $consignee;
        $order->shipping_mobile = $shipping_mobile;
        $order->shipping_address = $shipping_address;
        $order->refund_status = 0;
        $order->id_card = $id_card;
        $order->user_remark = $user_remark;
        return $order->save();

    }

    public function paySuccess($order_no,$pay_time,$pay_no,$thirdPartyCode){
        $order = Order::findOne(['order_no'=>$order_no]);
        if($order->order_status==0){
            $db=\Yii::$app->db;
            $transaction = $db->beginTransaction();
            $order->order_status = 1;
            $time = date('Y-m-d H:i:s');
            $order->pay_type = $thirdPartyCode;
            $order->pay_time = date('Y-m-d H:i:s',strtotime($pay_time));
            $order->pay_no = $pay_no;
            $order->update_time = $time;
            $result1 = $order->save();
            $mall = Mall::findOne($order->mall_id);
            $mall->order_num += 1;
            $result2 = $mall->save();
            if($result1 && $result2){
                $transaction->commit();
                return true;
            }else{
                $transaction->rollBack();
                return false;
            }
        }else{
            return false;
        }

    }

    public function beanstalkProducer($id,$type,$delay){
        $beanstalk = new Client(); // For connection options see the
        // class documentation.
        $beanstalk->connect();
        $beanstalk->useTube('order'); // Begin to use tube `'flux'`.
        $beanstalk->put(
            1, // Give the job a priority of 23.
            $delay,  // Do not wait to put job into the ready queue.
            60, // Give the job 1 minute to run.
            json_encode(['id'=>$id,'type'=>$type]) // The job's body.
            //$type=1:自动取消订单，$type=2:自动收货
        );
        $beanstalk->disconnect();
    }

    public function getOrderList($user_id,$page,$limit){
        $order = Order::find()
            ->select('order_id,order_no,order_amount,order_status,shipping_status,refund_status,update_time,goods_listpic,goods_name,goods_num')
            ->from('{{%order}} o')
            ->leftJoin('{{%goods}} g','g.goods_id=o.goods_id')
            ->where(['user_id'=>$user_id,'order_status'=>1])
            ->orderBy('order_id desc')
            ->offset($limit*($page-1))->limit($limit)
            ->asArray()->all();
        foreach($order AS &$value){
            $value['date'] = date('m-d',strtotime($value['update_time']));
            if($value['order_status']==1 && $value['shipping_status']==0 && $value['refund_status']==0)
                $value['status'] = 1;
            elseif($value['order_status']==1 && $value['shipping_status']==1 && $value['refund_status']==0)
                $value['status'] = 2;
            elseif($value['order_status']==1 && $value['refund_status']==1)
                $value['status'] = 3;
            elseif($value['order_status']==1 && $value['refund_status']==2)
                $value['status'] = 4;
            elseif($value['order_status']==1 && $value['refund_status']==3)
                $value['status'] = 2;
            elseif($value['order_status']==1 && $value['refund_status']==4)
                $value['status'] = 5;
            $value['goods_listpic'] = Yii::$app->params['pic_domain'].$value['goods_listpic'];
        }
        return $order;
    }

    public function pay($order_no){
        $pu = new PayUtil();
        $order = Order::find()->where(['order_no'=>$order_no])->asArray()->one();
        $orderGoods = OrderGoods::find()->where(['order_id'=>$order['order_id']])->asArray()->all();
        foreach ($orderGoods AS $value){
            $goods_name = $value['goods_name'];
            break;
        }
        $url = $pu->getUrl($order_no,date('YmdHis',strtotime($order['order_time'])),$order['order_amount'],$goods_name);
        return $url;
    }

    public function getOrderDetail($user_id,$order_no){
        $order = Order::find()
            ->select('order_id,order_no,order_amount,order_status,shipping_status,refund_status,order_time,goods_listpic,goods_name,goods_num,express_company,express_no,user_remark')
            ->from('{{%order}} o')
            ->leftJoin('{{%goods}} g','g.goods_id=o.goods_id')
            ->where(['user_id'=>$user_id,'order_no'=>$order_no])
            ->asArray()->one();
        $order['order_time'] = date('m-d',strtotime($order['order_time']));
        $order['goods_listpic'] = Yii::$app->params['pic_domain'].$order['goods_listpic'];
        return $order;
    }

    public function refund($user_id,$order_no,$reason){
        $db=\Yii::$app->db;
        $transaction = $db->beginTransaction();
        $order = Order::findOne(['user_id'=>$user_id,'order_no'=>$order_no]);
        if($order->refund_status==0) {
            $order->refund_status = 1;
            $result1 = $order->save();
            $refund = new Refund();
            $refund->refund_no = $this->createOrderNo();
            $refund->order_id = $order->order_id;
            $refund->refund_status = 1;
            $refund->refund_amount = $order->goods_amount;
            $refund->reason = $reason;
            $time = date('Y-m-d');
            $refund->add_time = $time;
            $refund->update_time = $time;
            $result2 = $refund->save();
            if ($result1 && $result2) {
                $transaction->commit();
            } else {
                $transaction->rollBack();
            }
        }
    }



}